package com.tjp.eight.ui.fragment.loginreg;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tjp.eight.LoginEvent;
import com.tjp.eight.R;
import com.tjp.eight.RxBus;
import com.tjp.eight.comment.AppManager;
import com.tjp.eight.constant.ConstantUtils;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.forgetpass.ActivityForGetPass;
import com.tjp.eight.ui.fragment.setpassword.ActivitySetPass;
import com.tjp.eight.utils.CodeUtils;
import com.tjp.eight.utils.DescriptUtils;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.DialogLogin;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2017/3/1.
 */
public class FragmentLogin extends BaseFragment<LogPresenter> implements LoginView {
    private ImageView iv_wx_login;
    private UMShareAPI umShareAPI;
    private View v_log;
    private View v_reg;
    private RelativeLayout rl_log;
    private RelativeLayout rl_reg;
    private RelativeLayout rl_code;
    private TextView tv_btn_log;
    private TextView tv_btn_reg;
    private TextView tv_login;
    private TextView tv_reg;
    private TextView tv_login_forget;
    private EditText et_log;
    private EditText et_pass;
    private EditText et_code;
    private ImageView reg_msg_code;
    private DialogLogin dialogLogin;
    private String wxUrl = "";
    private String gender = "";
    private String wxName = "";
    private boolean isWx = false;

    @Override
    protected LogPresenter createPresenter() {
        return new LogPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.login, container, false);
        }
        initViews();
        return contentView;
    }

    @Override
    public void RegSuccess(RegResultModel regResultModel) {
        if ("success".equals(regResultModel.result)) {
            Intent intent = new Intent(getActivity(), ActivitySetPass.class);
            intent.putExtra("phone", et_log.getText().toString());
            startActivityForResult(intent, 0x01);
        } else {
            Toast.makeText(getContext(), regResultModel.msg, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void RegFail(String msg) {
        ToatUtils.toastCommentFail(getContext(), msg);
    }

    @Override
    public void LoginSuccess(LoginResultModel loginResultModel) {
        dismissDialog();
        if (IsSuccessUtils.isSuccess(loginResultModel.result)) {
            SharePreferencesUtils.setLoginKey(loginResultModel.loginkey);
            SharePreferencesUtils.setUid(loginResultModel.uid);
            if (isWx) {
                SharePreferencesUtils.setName(wxName);
                SharePreferencesUtils.setGender(gender);
                SharePreferencesUtils.setUserUrl(wxUrl);
            }
            LoginEvent loginEvent = LoginEvent.getLoginEvent();
            loginEvent.login = true;
            loginEvent.logout = false;
            RxBus.getInstance().post(loginEvent);
            getActivity().setResult(0x01);
            AppManager.getAppManager().finishActivity(getActivity());
        } else {
            Toast.makeText(getContext(), "" + loginResultModel.msg, Toast.LENGTH_SHORT).show();
        }
        isWx = false;
    }

    @Override
    public void LoginFail(String msg) {
        dismissDialog();
        ToatUtils.toastCommentFail(getContext(), "" + msg);
    }

    @Override
    public void onShowDialog() {
        showDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0x01:
                //注册成功
                getActivity().setResult(0x01);
                AppManager.getAppManager().finishActivity(getActivity());
                break;
        }
    }

    void initViews() {
        reg_msg_code = (ImageView) contentView.findViewById(R.id.reg_msg_code);
        Bitmap bitmap = CodeUtils.getInstance().createBitmap();
        reg_msg_code.setImageBitmap(bitmap);
        reg_msg_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reg_msg_code.setImageBitmap(CodeUtils.getInstance().createBitmap());
            }
        });
        v_log = contentView.findViewById(R.id.v_login);
        v_reg = contentView.findViewById(R.id.v_reg);
        rl_log = (RelativeLayout) contentView.findViewById(R.id.rl_login);
        rl_reg = (RelativeLayout) contentView.findViewById(R.id.rl_reg);
        rl_code = (RelativeLayout) contentView.findViewById(R.id.rl_code);
        tv_btn_log = (TextView) contentView.findViewById(R.id.tv_btn_login);
        tv_btn_reg = (TextView) contentView.findViewById(R.id.tv_btn_reg);
        tv_login_forget = (TextView) contentView.findViewById(R.id.tv_login_forget);
        tv_login = (TextView) contentView.findViewById(R.id.tv_login);
        tv_reg = (TextView) contentView.findViewById(R.id.tv_reg);
        et_log = (EditText) contentView.findViewById(R.id.et_log_phone);
        et_pass = (EditText) contentView.findViewById(R.id.et_log_pass);
        et_code = (EditText) contentView.findViewById(R.id.et_code);
        tv_login_forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ActivityForGetPass.class));
            }
        });
        rl_log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setLoginSelected();
            }
        });
        rl_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setRegSelected();
            }
        });
        et_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changRegTv();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_log.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changLogTv();
                changRegTv();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_pass.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(" ")) {
                    String[] str = s.toString().split(" ");
                    String str1 = "";
                    for (int i = 0; i < str.length; i++) {
                        str1 += str[i];
                    }
                    et_pass.setText(str1);

                    et_pass.setSelection(start);

                }
                changLogTv();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        try {
            Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
            field.setAccessible(true);
            field.set(et_pass, R.drawable.cursor_style);
            field.set(et_log, R.drawable.cursor_style);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        tv_btn_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!CodeUtils.getInstance().getCode().equals(et_code.getText().toString())) {
                    Toast.makeText(getContext(), "验证码输入错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                RegModel regModel = new RegModel();
                String time = System.currentTimeMillis() / 1000 + "";

                regModel.mobile = et_log.getText().toString();
                regModel.time = time;
                regModel.authcode = CodeUtils.getInstance().getCode();
                regModel.md5authcode = DescriptUtils.SHA1(time + regModel.authcode + regModel.authcode + ConstantUtils.SHA1);
                Gson gson = new Gson();
                String json = gson.toJson(regModel);
                presenter.toRegPhone(json);
            }
        });
        tv_btn_log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
                LoginPhoneModel loginPhoneModel = new LoginPhoneModel();
                loginPhoneModel.mobile = et_log.getText().toString();
                loginPhoneModel.pwd = et_pass.getText().toString();
                String json = new Gson().toJson(loginPhoneModel);
                presenter.toLoginPhone(json);

            }
        });

        setLoginSelected();

        umShareAPI = UMShareAPI.get(getContext());
        iv_wx_login = (ImageView) contentView.findViewById(R.id.iv_wx_login);
        iv_wx_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isWx = true;
                showDialog();
                umShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, umAuthListenerMsg);
            }
        });
    }

    void showDialog() {
        if (dialogLogin == null) {
            dialogLogin = new DialogLogin(getActivity());
        }
        dialogLogin.show();
    }

    void dismissDialog() {
        if (dialogLogin == null) {
            dialogLogin = new DialogLogin(getActivity());
        }
        dialogLogin.dismiss();
    }

    private UMAuthListener umAuthListenerMsg = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            LoginModel loginModel = new LoginModel();
            loginModel.openid = map.get("openid");
            loginModel.unionid = map.get("unionid");
            loginModel.name = map.get("name");
            loginModel.gender = map.get("gender");
            loginModel.iconurl = map.get("iconurl");

            wxUrl = loginModel.iconurl;
            wxName = loginModel.name;
            gender = loginModel.gender;

            Random random = new Random();
            loginModel.authcode = random.nextInt(999999) + "";
            String time = System.currentTimeMillis() / 1000 + "";
            loginModel.time = time;
            loginModel.md5authcode = DescriptUtils.SHA1(time + loginModel.authcode + loginModel.authcode + ConstantUtils.SHA1);

            Gson gson = new Gson();
            String json = gson.toJson(loginModel);
            isWx = true;
            presenter.toLoginWX(json);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            isWx = false;
            Toast.makeText(getContext(), "授权失败", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            isWx = false;
            Toast.makeText(getContext(), "授权取消", Toast.LENGTH_LONG).show();
        }
    };

    private void setLoginSelected() {
        v_reg.setVisibility(View.INVISIBLE);
        v_log.setVisibility(View.VISIBLE);
        et_pass.setVisibility(View.VISIBLE);
        rl_code.setVisibility(View.GONE);
        tv_login_forget.setVisibility(View.VISIBLE);
        tv_btn_reg.setVisibility(View.GONE);
        tv_btn_log.setVisibility(View.VISIBLE);
        tv_login.setSelected(true);
        tv_reg.setSelected(false);
    }

    private void setRegSelected() {
        v_reg.setVisibility(View.VISIBLE);
        v_reg.setVisibility(View.VISIBLE);
        v_log.setVisibility(View.INVISIBLE);
        et_pass.setVisibility(View.GONE);
        rl_code.setVisibility(View.VISIBLE);
        tv_login_forget.setVisibility(View.INVISIBLE);
        tv_btn_reg.setVisibility(View.VISIBLE);
        tv_btn_log.setVisibility(View.GONE);
        tv_login.setSelected(false);
        tv_reg.setSelected(true);
    }

    private void changLogTv() {
        if (et_log.getText().toString().length() == 11
                && et_pass.getText().toString().length() >= 6 && StringUtils.isMobileNO(et_log.getText().toString())) {
            tv_btn_log.setEnabled(true);
        } else {
            tv_btn_log.setEnabled(false);
        }
    }

    private void changRegTv() {
        if (et_log.getText().toString().length() == 11
                && StringUtils.isMobileNO(et_log.getText().toString())
                && et_code.getText().toString().length() == 6) {
            tv_btn_reg.setEnabled(true);
        } else {
            tv_btn_reg.setEnabled(false);
        }
    }
}
